<template>
	<view>
		<h1>测试webSocket</h1>
		<label>你的id</label><input v-model="yourId" type="text">
		<button @click="initWebSocket">连接</button>
		<label>对方id</label><input v-model="otherId" type="text">
		<button @click="getWebsocket">点击请求后台数据</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				yourId: '',
				otherId: ''
			}
		},
		created() { // 页面创建生命周期函数              
			// this.initWebSocket()
		},
		destroyed: function() { // 离开页面生命周期函数              
			this.websocketclose();
		},
		methods: {
			initWebSocket: function() {
				// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https                
				this.websock = new WebSocket("ws://localhost:8080/websocket/" + this.yourId);
				this.websock.onopen = this.websocketonopen;
				this.websock.onerror = this.websocketonerror;
				this.websock.onmessage = this.websocketonmessage;
				this.websock.onclose = this.websocketclose;
			},
			websocketonopen: function() {
				console.log("WebSocket连接成功");
			},
			websocketonerror: function(e) {
				console.log("WebSocket连接发生错误");
			},
			websocketonmessage: function(e) {
				console.log("===============")
				console.log(e)
				console.log(e.data); // console.log(e);              
				console.log("===============")
			},
			websocketclose: function(e) {
				console.log("connection closed (" + e.code + ")");
			},
			getWebsocket: function() {
				let url = `http://localhost:8080/api/teachStf/import?shipId=${this.otherId}`
				// 这里只是一个基于axios的ajax请求，你可以换成你的请求格式                
				// this.$ajax.get(url)
				uni.request({
					url: url,
					success: (res) => {
						console.log(res)
						console.log(res.data)
					}
				})
			}
		}
	}
</script>

<style>

</style>
